/**
 * 移动端性能优化工具
 * 提供图片懒加载、虚拟滚动、防抖节流等功能
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

// 防抖函数
export const debounce = (func, wait, immediate = false) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      timeout = null;
      if (!immediate) func(...args);
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func(...args);
  };
};

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle;
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 图片懒加载
export class LazyImageLoader {
  constructor(options = {}) {
    this.options = {
      root: null,
      rootMargin: '50px',
      threshold: 0.1,
      placeholder: '',
      ...options
    };
    this.observer = null;
    this.init();
  }

  init() {
    if ('IntersectionObserver' in window) {
      this.observer = new IntersectionObserver(
        this.handleIntersection.bind(this),
        this.options
      );
    }
  }

  observe(element) {
    if (this.observer && element) {
      this.observer.observe(element);
    }
  }

  unobserve(element) {
    if (this.observer && element) {
      this.observer.unobserve(element);
    }
  }

  handleIntersection(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        const src = img.dataset.src;
        
        if (src) {
          img.src = src;
          img.classList.remove('lazy');
          img.classList.add('loaded');
          this.unobserve(img);
        }
      }
    });
  }

  destroy() {
    if (this.observer) {
      this.observer.disconnect();
    }
  }
}

// 虚拟滚动
export class VirtualScroll {
  constructor(container, options = {}) {
    this.container = container;
    this.options = {
      itemHeight: 50,
      buffer: 5,
      ...options
    };
    this.scrollTop = 0;
    this.containerHeight = 0;
    this.totalItems = 0;
    this.visibleItems = [];
    this.startIndex = 0;
    this.endIndex = 0;
    
    this.init();
  }

  init() {
    this.containerHeight = this.container.clientHeight;
    this.updateVisibleItems();
    
    this.container.addEventListener('scroll', this.handleScroll.bind(this));
    window.addEventListener('resize', this.handleResize.bind(this));
  }

  handleScroll() {
    this.scrollTop = this.container.scrollTop;
    this.updateVisibleItems();
  }

  handleResize() {
    this.containerHeight = this.container.clientHeight;
    this.updateVisibleItems();
  }

  updateVisibleItems() {
    const { itemHeight, buffer } = this.options;
    const visibleCount = Math.ceil(this.containerHeight / itemHeight);
    
    this.startIndex = Math.max(0, Math.floor(this.scrollTop / itemHeight) - buffer);
    this.endIndex = Math.min(
      this.totalItems - 1,
      this.startIndex + visibleCount + buffer * 2
    );
    
    this.visibleItems = Array.from(
      { length: this.endIndex - this.startIndex + 1 },
      (_, i) => this.startIndex + i
    );
  }

  setTotalItems(count) {
    this.totalItems = count;
    this.updateVisibleItems();
  }

  getVisibleItems() {
    return this.visibleItems;
  }

  getOffsetY() {
    return this.startIndex * this.options.itemHeight;
  }

  destroy() {
    this.container.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('resize', this.handleResize);
  }
}

// 移动端性能监控
export class MobilePerformanceMonitor {
  constructor() {
    this.metrics = {};
    this.observers = [];
    this.init();
  }

  init() {
    // 监控页面加载性能
    this.observePageLoad();
    
    // 监控长任务
    this.observeLongTasks();
    
    // 监控内存使用
    this.observeMemoryUsage();
    
    // 监控网络状态
    this.observeNetworkStatus();
  }

  observePageLoad() {
    if ('performance' in window) {
      window.addEventListener('load', () => {
        const navigation = performance.getEntriesByType('navigation')[0];
        this.metrics.pageLoad = {
          domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
          loadComplete: navigation.loadEventEnd - navigation.loadEventStart,
          totalTime: navigation.loadEventEnd - navigation.fetchStart
        };
      });
    }
  }

  observeLongTasks() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          if (entry.duration > 50) { // 超过50ms的任务
            console.warn('Long task detected:', entry.duration + 'ms');
          }
        }
      });
      
      try {
        observer.observe({ entryTypes: ['longtask'] });
        this.observers.push(observer);
      } catch (e) {
        console.warn('Long task observer not supported');
      }
    }
  }

  observeMemoryUsage() {
    if ('memory' in performance) {
      setInterval(() => {
        this.metrics.memory = {
          used: performance.memory.usedJSHeapSize,
          total: performance.memory.totalJSHeapSize,
          limit: performance.memory.jsHeapSizeLimit
        };
      }, 5000);
    }
  }

  observeNetworkStatus() {
    if ('connection' in navigator) {
      this.metrics.network = {
        effectiveType: navigator.connection.effectiveType,
        downlink: navigator.connection.downlink,
        rtt: navigator.connection.rtt
      };
    }
  }

  getMetrics() {
    return this.metrics;
  }

  destroy() {
    this.observers.forEach(observer => observer.disconnect());
  }
}

// 移动端优化配置
export const mobileOptimizations = {
  // 图片优化
  imageOptimization: {
    quality: 0.8,
    format: 'webp',
    sizes: '(max-width: 480px) 100vw, (max-width: 768px) 50vw, 33vw'
  },
  
  // 字体优化
  fontOptimization: {
    display: 'swap',
    preload: true
  },
  
  // 代码分割
  codeSplitting: {
    chunkSize: 244 * 1024, // 244KB
    maxChunks: 5
  },
  
  // 缓存策略
  cacheStrategy: {
    static: 'max-age=31536000', // 1年
    dynamic: 'max-age=3600', // 1小时
    api: 'max-age=300' // 5分钟
  }
};

// 移动端检测
export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};

// 触摸设备检测
export const isTouchDevice = () => {
  return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
};

// 网络状态检测
export const getNetworkStatus = () => {
  if ('connection' in navigator) {
    const connection = navigator.connection;
    return {
      effectiveType: connection.effectiveType,
      downlink: connection.downlink,
      rtt: connection.rtt,
      saveData: connection.saveData
    };
  }
  return null;
};

// 设备像素比检测
export const getDevicePixelRatio = () => {
  return window.devicePixelRatio || 1;
};

// 视口尺寸获取
export const getViewportSize = () => {
  return {
    width: window.innerWidth,
    height: window.innerHeight
  };
};

// 移动端性能建议
export const getPerformanceRecommendations = () => {
  const recommendations = [];
  
  if (getDevicePixelRatio() > 2) {
    recommendations.push('考虑使用高分辨率图片');
  }
  
  const network = getNetworkStatus();
  if (network && network.effectiveType === 'slow-2g') {
    recommendations.push('网络较慢，建议启用数据压缩');
  }
  
  if (isMobile()) {
    recommendations.push('移动设备，建议启用触摸优化');
  }
  
  return recommendations;
};
